#include "FWDirectShow.h"



FWDirectShow::FWDirectShow(void)
{
	this->_graphBuilder = NULL;
	this->_mediaControl = NULL;
	this->_mediaEventEx = NULL;
	this->_mediaSeeking = NULL;
	this->_isPlaying = false;
}


FWDirectShow::~FWDirectShow(void)
{
}

void FWDirectShow::initialize()
{
	//create instance of graph builder
	CoCreateInstance(CLSID_FilterGraph, NULL, CLSCTX_INPROC_SERVER, IID_IGraphBuilder, (void**)&this->_graphBuilder);
	if(!this->_graphBuilder)
	{
		MessageBox(NULL, "can't create graph builder", "ERROR", MB_OK);
		return;
	}
	//get reference to interface
	this->_graphBuilder->QueryInterface(IID_IMediaControl, (void**)&this->_mediaControl);
	this->_graphBuilder->QueryInterface(IID_IMediaSeeking, (void**)&this->_mediaSeeking);
	this->_graphBuilder->QueryInterface(IID_IMediaEventEx, (void**)&this->_mediaEventEx);
	if(!this->_mediaControl || !this->_mediaEventEx || !this->_mediaSeeking)
	{
		MessageBox(NULL, "can't query interface", "ERROR", MB_OK);
		return;
	}
	this->_isPlaying = false;
}

void FWDirectShow::load(LPCTSTR fileName)
{
	WCHAR* wfileName = new WCHAR[256];
	//convert fileName to WCHAR*
	mbstowcs(wfileName, fileName, 256);
	//builds a filter graph
	this->_graphBuilder->RenderFile(wfileName, NULL);
	this->_isPlaying = false;
	this->_isReady = true;
}

void FWDirectShow::play()
{
	if(this->_mediaControl && this->_isReady)
	{
		//play
		this->_mediaControl->Run();
	}	
}

void FWDirectShow::pause()
{
	if(this->_mediaControl != NULL)
	{
		if(this->_isPlaying)
		{
			this->_mediaControl->Pause();
			this->_isPlaying = false;
		}
	}
}

void FWDirectShow::resume()
{
	if (this->_mediaControl != NULL)
	{
		if(!this->_isPlaying)
		{
			this->_mediaControl->Run();
			this->_isPlaying = true;
		}
	}
}

void FWDirectShow::stop()
{
	if (this->_mediaControl != NULL)
	{
		if (this->_isPlaying)
		{
			this->_mediaControl->Stop();
			this->_isPlaying = false;
		}
	}
}